﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Input;
using System.Windows.Data;

namespace QuickTweet.Common.Commanding
{
    public class DelegateCommand : DependencyObject, ICommand
    {
        private Action<object> _executeDelegate;
        public event EventHandler CanExecuteChanged;

        public bool CanExecuteAction
        {
            get { return (bool)GetValue(CanExecuteActionProperty); }
            set { SetValue(CanExecuteActionProperty, value); }
        }

        public static readonly DependencyProperty CanExecuteActionProperty =
               DependencyProperty.Register("CanExecuteAction", typeof(bool), typeof(DelegateCommand),
                                           new PropertyMetadata(OnCanExecuteActionChanged));

        public DelegateCommand(Action<object> executeDelegate) : this(executeDelegate, null) { }        

        public DelegateCommand(Action<object> executeDelegate, Binding canExecuteActionBinding)
        {
            _executeDelegate = executeDelegate;
            if (canExecuteActionBinding != null)
                BindingOperations.SetBinding(this, CanExecuteActionProperty, canExecuteActionBinding);
        }

        #region ICommand Members

        public void Execute(object parameter) 
        { 
            if (_executeDelegate != null)
                _executeDelegate(parameter); 
        }

        public bool CanExecute(object parameter) 
        {
            if (BindingOperations.GetBinding(this, CanExecuteActionProperty) == null)
                return true;

            return CanExecuteAction; 
        }

        #endregion

        private void RaiseCanExecuteActionChanged()
        {
            if (CanExecuteChanged != null) 
                CanExecuteChanged(this, new EventArgs());
        }

        static void OnCanExecuteActionChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
        {
            (dependencyObject as DelegateCommand).RaiseCanExecuteActionChanged();
        }
    }
}
